package com.aaa.gs.filter;

import com.aaa.common.util.Result;
import com.aaa.common.util.ResultStatus;
import com.alibaba.fastjson.JSON;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.io.UnsupportedEncodingException;

/**
 * @ FileName: IllegalIPFilter
 * @ Description:
 * @ Author:  STB
 * @ CreateTime: 2025/9/2 0002 19:05
 * @ Version: 1.0.0
 */
@Component
@Log4j2
public class IllegalIPFilter implements GlobalFilter, Ordered {

    @Value("${illegal_ip}")
    private String illegalIp;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //exchange 包含request和response
        log.info("----------------------经过了非法IP过滤器----------------------");
        //获取当前请求IP
        //获取request对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取Ip
        String ip = request.getRemoteAddress().getAddress().getHostAddress();
        log.info("当前请求的IP为："+ip);
        //判断
        //"172.16.8.60,172.16.8.53,172.16.8.81,172.16.8.70,172.16.8.78,172.16.8.90".contains("172.16.8.90")
        if(illegalIp.contains(ip)){
            // 不合法则返回错误信息
            Result result =new Result(ResultStatus.ILLEGAL_IP.getReturnCode(),
                    ResultStatus.ILLEGAL_IP.getReturnMessage(),"非法IP错误！！！！！！！！");

            try {
                byte[] datas = JSON.toJSONString(result).getBytes("utf-8");
                DataBuffer buffer = response.bufferFactory().wrap(datas);
                //添加响应头
                response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
                //写入自定义错误信息，并返回
                return response.writeWith(Mono.just(buffer));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        //chain.filter(exchange) 让程序继续运行
        return chain.filter(exchange);
    }

    /**
     * 当有多个filter同时存在时，使用当前方法决定优先级  当前方法返回值越小，优先级越高
     *    数字取值范围就是Integer 取值范围: -2^31----------2&31-1
     * @return
     */
    @Override
    public int getOrder() {
        return 1000;
    }
}
